<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        background-color: #333;
      }
    </style>
  </head>
  <body>
    <button>按钮</button>
    <input type="text" />
    <button class="cancle">取消</button>

    <script>
      // 当事件触发时不会立即执行,而是等待一定时间再触发.如果事件密集触发,函数的触发会被频繁推迟
      const btnEl = document.querySelector('button');
      const inputEl = document.querySelector('input');
      const cancleBtnEl = document.querySelector('.cancle');

      // 防抖函数
      function myDebounce(callback, delay) {
        let timer = null;

        const execution = function (...args) {
          if (timer) clearTimeout(timer);
          timer = setTimeout(() => {
            try {
              callback.apply(this, args);
            } catch (error) {
              console.error('Error in debounce function:', error);
            }
            timer = null;
          }, delay);
        };

        // 绑定一个取消函数
        execution.cancel = function () {
          if (timer) clearTimeout(timer);
          timer = null;
        };

        return execution;
      }

      const debounce = myDebounce(function (event) {
        console.log(this, 'event:', event);
      }, 500);

      // 输入事件
      inputEl.addEventListener('input', debounce);

      // 取消事件
      cancleBtnEl.addEventListener('click', () => {
        debounce.cancel();
      });
    </script>
  </body>
</html>
